﻿/*
* 命名空间: Authority.Logic
*
* 功 能： 岗位功能管理逻辑
*
* 类 名： SysPostServiceImpl
*
* Version   变更日期            负责人     变更内容
* ─────────────────────────────────────────────────
* V1.0.1    2020/03/17 14:34:43 李聪     创建
*
* Copyright (c) 2020 Lir Corporation. All rights reserved.
*/
using System.Collections.Generic;
using Authority.Model;
using Common.Model;
using Dapper.Library.DataAccessSql;
using Dapper.PostgreSql.Library;
using Common.Library;
using Container.Library;
using System;
using System.Linq;
using Dapper.Library;
using Serialize.Library;

namespace Authority.Logic
{
    /// <summary>
    /// 岗位功能管理逻辑
    /// </summary>
    public class SysPostServiceImpl : OperationLogicImpl, ISysPostService
    {
        #region 岗位基础信息管理模块

        #region 查询
        /// <summary>
        /// 获取所有岗位数据
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<PostResponse>> LoadSysPostAllList()
        {
            var resultInfo = new ResultJsonInfo<List<PostResponse>>();

            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                var result = con.QuerySet<SysPostInfoEntity>().Where(a => a.is_deleted == false).ToList();

                resultInfo.Code = ActionCodes.Success;
                resultInfo.Data = result.MapToList<PostResponse>();

            }
            return resultInfo;
        }

        /// <summary>
        /// 获取所有岗位树状数据
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<SelectListInfo>> LoadSysPostTreeList()
        {
            var resultInfo = new ResultJsonInfo<List<SelectListInfo>>();

            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                var result = con.QuerySet<SysPostInfoEntity>().Where(a => a.is_deleted == false && a.is_valid == true).ToList();

                resultInfo.Code = ActionCodes.Success;
                resultInfo.Data = result.MapToList<SelectListInfo>();

            }
            return resultInfo;
        }

        /// <summary>
        /// 根据岗位关键字 分页获取岗位列表
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<PostResponse>> LoadSysPostList(ParametersInfo<string> inputInfo)
        {
            var resultInfo = new ResultJsonInfo<List<PostResponse>>();

            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                var result = con.QuerySet<SysPostInfoEntity>().Where(a => a.is_deleted == false);
                if (inputInfo.parameters.IsNotNullOrEmpty())
                {
                    result.Where(a => a.name.Contains(inputInfo.parameters));
                }
                if (inputInfo.order.ToLower() == "asc")
                {
                    result.OrderBy(inputInfo.field);
                }
                else
                {
                    result.OrderByDescing(inputInfo.field);
                }
                var listInfo = result.PageList(inputInfo.page, inputInfo.limit);

                if (listInfo.Items.Count > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = listInfo.Items.MapToList<PostResponse>();
                    resultInfo.Count = listInfo.Total;
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }

            }

            return resultInfo;
        }

        /// <summary>
        /// 获取单个岗位的信息
        /// </summary>
        /// <param name="postId">岗位ID</param>
        /// <returns></returns>
        public ResultJsonInfo<PostResponse> LoadSysPostListOne(string postId)
        {
            var resultInfo = new ResultJsonInfo<PostResponse>();

            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                var result = con.QuerySet<SysPostInfoEntity>().Where(a => a.id == postId).Get();

                if (result != null)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = result.MapTo<PostResponse>();
                    resultInfo.Msg = "处理成功！";
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 根据部门id获取用户情况
        /// </summary>
        /// <param name="queryInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<PostUserResponse>> LoadListInfoByPostId(PostUserQueryRequest queryInfo)
        {
            var resultInfo = new ResultJsonInfo<List<PostUserResponse>>();

            var userList = new List<PostUserResponse>();

            List<SysUserInfoEntity> listInfo = null;
            List<SysUserPostReEntity> sysPostUser = null;

            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {

                con.Transaction(tran =>
                {

                    listInfo = tran.QuerySet<SysUserInfoEntity>()
                              .Where(p => p.is_deleted == false && p.is_valid == true)
                              .OrderBy(p => p.sort)
                              .ToList();

                    sysPostUser = tran.QuerySet<SysUserPostReEntity>()
                        .Join<SysUserPostReEntity, SysUserInfoEntity>((a, b) => a.user_id == b.id)
                        .From<SysUserPostReEntity, SysUserInfoEntity>()
                        .OrderBy<SysUserInfoEntity>(p => p.sort)
                        .Where((a, b) => b.is_valid == true && a.post_id == queryInfo.postid)
                        .ToList((a, b) => new SysUserPostReEntity
                        {
                            id = a.id,
                            post_id = a.post_id,
                            user_id = a.user_id
                        });

                    userList = listInfo.MapToList<PostUserResponse>();

                    foreach (var item in userList)
                    {
                        if (sysPostUser.Exists(p => p.user_id == item.id))
                        {
                            item.lay_is_checked = true;
                        }
                    }
                });
            }

            if (listInfo.Count > 0)
            {
                resultInfo.Code = ActionCodes.Success;
                resultInfo.Data = userList;
                resultInfo.Count = userList.Count;
                resultInfo.Msg = "获取成功！";
            }
            else
            {
                resultInfo.Msg = "无对应信息！";
            }
            return resultInfo;
        }
        #endregion

        #region 添加
        /// <summary>
        /// 新增一个岗位
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> AddSysPost(PostAddRequest postAdd)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                var user = GetLoginUserInfo();

                var sysPost = postAdd.MapTo<SysPostInfoEntity>();

                sysPost.creator_id = user.id;
                sysPost.creator_name = user.name;
                sysPost.modifier_date = DateTime.Now;
                sysPost.modifier_id = user.id;
                sysPost.modifier_name = user.name;

                var result = con.CommandSet<SysPostInfoEntity>()
                     .IfNotExists(p => p.name)
                     .Insert(sysPost);

                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "添加成功！";
                    AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.PostManage, $"添加了一个新的岗位，新增岗位信息：{JsonHelper.ToJson(sysPost)}");
                }
                else
                {
                    resultInfo.Code = ActionCodes.InvalidOperation;
                    resultInfo.Msg = "添加失败！";
                }
            }

            return resultInfo;
        }
        #endregion

        #region 修改
        /// <summary>
        /// 修改一个岗位
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> ModifySysPost(PostModifyRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                var user = GetLoginUserInfo();

                var postInfo = con.QuerySet<SysPostInfoEntity>().Where(p => p.id == inputInfo.id).Get();
                if (postInfo != null)
                {
                    postInfo.remarks = inputInfo.remarks;
                    postInfo.name = inputInfo.name;
                    postInfo.sort = inputInfo.sort;
                    postInfo.brevity_code = inputInfo.brevity_code;
                    postInfo.modifier_date = DateTime.Now;
                    postInfo.modifier_id = user.id;
                    postInfo.modifier_name = user.name;


                    var result = con.CommandSet<SysPostInfoEntity>().Update(postInfo);
                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "操作成功！";
                        AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.PostManage, $"修改岗位成功，修改岗位信息：{JsonHelper.ToJson(postInfo)}");
                    }
                    else
                    {
                        resultInfo.Msg = $"岗位{postInfo.name}修改失败！";
                    }
                }
                else
                {
                    resultInfo.Code = ActionCodes.ArgumentInvalid;
                    resultInfo.Msg = "ID无效！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 删除岗位
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> DeleteSysPost(List<string> postIds)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                var user = GetLoginUserInfo();
                //var postInfo = con.QuerySet<SysPostInfoEntity>().Where(a => postIds.Contains(a.id)).ToList();

                var arrPostIds = postIds.ToArray();

                var postInfo = con.QuerySet<SysPostInfoEntity>().Where(a => a.id.PostIn(arrPostIds)).ToList();

                
                //事务功能
                con.Transaction(tran =>
                {
                    var result = 0;
                    foreach (var item in postInfo)
                    {
                        item.is_deleted = true;
                        item.modifier_date = DateTime.Now;
                        item.modifier_id = user.id;
                        item.modifier_name = user.name;
                        result = tran.CommandSet<SysPostInfoEntity>().Update(item);
                    }


                    //删除原来配置的岗位数据
                    var deletezhi = tran.CommandSet<SysUserPostReEntity>().Where(a => a.post_id.PostIn(arrPostIds)).Delete();

                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "操作成功！";
                        AddOperationLog(OperationLogType.RemoveOperation, BusinessTitleType.PostManage, $"批量删除岗位成功，批量删除岗位信息：{JsonHelper.ToJson(postInfo)}");
                    }
                    else
                    {
                        resultInfo.Msg = "批量删除岗位失败！";
                    }
                }, ex =>
                {
                    throw ex;
                });


            }
            return resultInfo;
        }
        /// <summary>
        /// 禁用/启用岗位
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> ForbiddenSysPost(string postId)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                var user = GetLoginUserInfo();
                var postInfo = con.QuerySet<SysPostInfoEntity>().Where(p => p.id == postId).Get();
                if (postInfo != null)
                {
                    if (postInfo.is_valid)
                    {
                        postInfo.is_valid = false;
                    }
                    else
                    {
                        postInfo.is_valid = true;
                    }
                    postInfo.modifier_date = DateTime.Now;
                    postInfo.modifier_id = user.id;
                    postInfo.modifier_name = user.name;

                    var result = con.CommandSet<SysPostInfoEntity>().Update(postInfo);
                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "操作成功！";

                        AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.PostManage, $"禁用/启用岗位成功，禁用/启用岗位信息：{JsonHelper.ToJson(postInfo)}");
                    }
                    else
                    {
                        resultInfo.Msg = $"岗位{postInfo.name} 禁用/启用失败！";
                    }
                }
                else
                {
                    resultInfo.Code = ActionCodes.ArgumentInvalid;
                    resultInfo.Msg = "ID无效！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 修改对应岗位下对应的用户
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> ModifyPostUserInfo(PostUserModifyRequest post)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                con.Transaction(tran =>
                {
                    var userCodes = post.menuIdList;

                    #region 获取当前选中节点和选中节点的子节点
                    var allInfo = tran.QuerySet<SysUserInfoEntity>().Where(p => p.is_deleted == false && p.is_valid == true)
                                                                .OrderBy(p => p.sort)
                                                                .ToList();
                    var deoarInfo = allInfo.FindAll(p => userCodes.Contains(p.id));

                    var listInfo = new List<SysUserInfoEntity>();
                    if (deoarInfo.Count > 0)
                    {
                        listInfo.AddRange(deoarInfo);

                    }
                    userCodes = listInfo.Select(t => t.id).Distinct().ToList();

                    #endregion

                    //获取该岗位原有的用户
                    var deparUserListInfo = tran.QuerySet<SysUserPostReEntity>()
                                    .Where(p => p.post_id.Equals(post.post_id))
                                    .ToList();

                    //1、获取需要删除的，删除掉。
                    var needRemoveDeparUserListInfo = deparUserListInfo.FindAll(p => !userCodes.Contains(p.user_id))
                                    .Select(p => p.user_id)
                                    .ToArray();

                    //删除掉不用的用户
                    tran.CommandSet<SysUserPostReEntity>()
                                    .Where(p => p.user_id.PostIn(needRemoveDeparUserListInfo) && p.post_id.Equals(post.post_id))
                                    .Delete();

                    //2、获取需要增加的，增加上。
                    var needAddDeparUserListInfo = userCodes.ToList()
                                    .FindAll(p => !deparUserListInfo.Select(roleMenu => roleMenu.user_id).Contains(p));

                    SysUserPostReEntity deparUserItem = null;
                    foreach (var item in needAddDeparUserListInfo)
                    {
                        deparUserItem = new SysUserPostReEntity();
                        deparUserItem.id = GuidHelper.GetGuid();
                        deparUserItem.post_id = post.post_id;
                        deparUserItem.user_id = item;
                        tran.CommandSet<SysUserPostReEntity>().Insert(deparUserItem);
                    }
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = 1;
                    resultInfo.Msg = "操作成功！";
                });
            }
            return resultInfo;
        }

        #endregion

  

        #endregion
    }
}
